package fr.grassaud.hmvc.application;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import fr.grassaud.hmvc.session.HMVCSession;
import fr.grassaud.hmvc.session.HMVCSessionFactory;
import fr.grassaud.hmvc.session.SessionTriadListener;

public abstract class HMVCSwingApplication implements HMVCApplication {

    private HMVCSessionFactory hmvcSessionFactory;

    public void onStart() {

    }

    public void afterStart() {

    }

    public void start() {

	hmvcSessionFactory = getHMVCSessionFactory();

	hmvcSessionFactory.setRootControllerClass(getRootControllerClass());
	for (SessionTriadListener listener : getSessionTriadListeners()) {
	    hmvcSessionFactory.addTriadListener(listener);
	}
	onStart();

	SwingUtilities.invokeLater(new Runnable() {

	    @Override
	    public void run() {
		HMVCSession session = hmvcSessionFactory.newSession();
		// Main view in a swing context should be a JFrame
		final JFrame frame = session.getMainView();
		frame.setVisible(true);
		afterStart();

	    }
	});

    }

    @Override
    public HMVCSessionFactory getHMVCSessionFactory() {
	if (hmvcSessionFactory == null) {
	    hmvcSessionFactory = new HMVCSessionFactory();
	}
	return hmvcSessionFactory;
    }

}
